/*
 * @Descripttion:
 * @version: 1.0.0
 * @Author: Shentong
 * @Date: 2021-04-09 12:34:34
 * @LastEditors: Shentong
 * @LastEditTime: 2021-11-22 16:12:04
 */
// eslint-disable-next-line @typescript-eslint/no-use-before-define
 import React, {  useState } from "react";
import { connect } from 'react-redux'
import Taro, { useDidShow } from '@tarojs/taro'

 import { View, Image, Button } from "@tarojs/components";

import { showToast } from '@/utils/index'
import { authorization } from '@/src/api/user'


 import AappIcon from '@/src/assets/icon/appIcon.jpeg'

 import styles from './index.module.scss'

 const Authorization = (props) => {
   const { dispatch } = props

   const [userImpower, setUserImpower] = useState(false)
   const [loginImpower, setLoginImpower] = useState(false)
   const [avatarUrl, setAvatarUrl] = useState<string>('')
   const [nickName, setNickName] = useState<string>('')
   const [code, setCode] = useState<string>('')

   // 获取本地存储的用户信息，控制页面显示状态
   const getStorageUserInfo = () => {
    const { avatarUrl: avatar,  nickName: name} = Taro.getStorageSync('userInfo') || {}
    const token = Taro.getStorageSync('token') || ''

    if (name) {
      setStorage({
        token,
        userInfo: { avatarUrl:avatar , nickName: name }
      }).then(() => {
        setUserImpower(true)
      })
    }
  }

  // 登录成功设置本地信息
  const setStorage = payload => {
    const { token = '', userInfo } = payload

    dispatch({ type: 'LOGIN', payload: { token, userInfo } })

    const getUserInfo = Taro.getStorageSync('userInfo') || {}

    return Promise.all([
      Taro.setStorageSync('token', token),
      Taro.setStorageSync('userInfo', Object.assign(getUserInfo, userInfo)),
    ])

  }

  // 获取用户头像
  const getUserInfoHandle = () => {
    Taro.getUserProfile({
      lang: 'zh_CN',
      desc: '获取您的昵称、头像、地区及性别',
      success: response => {
        const { userInfo: { nickName = '', avatarUrl = '' } = {} } = response

        setStorage({ userInfo: { avatarUrl , nickName } }).then(() => {
          setUserImpower(true)
        })
      },
      fail: err => {
        console.log('您拒绝了请求', err)
      }
    })
  }

  // 获取手机号
  const getPhoneNumberHandle = (e) => {
    console.log('eeee', e)
    const { detail: { encryptedData = '', iv = '' } = {}} = e
    if (encryptedData && iv) taroLogin({ encryptedData, iv })
  }

  // 微信用户授权登录
  const taroLogin = async ({ encryptedData, iv }) => {
    Taro.showLoading({ title: '正在登录', mask: true })

    const params = { encryptedData, iv, code }
    try {

      const res = await authorization(params)

      if (res.code === '00000-00000') { // 成功
        // 46E738C9B5A79E06F0DADD32CC575844E9738B57723ECF0035FB85E921A2BB0550A9D95C7D1E53778CA7E7682BD5F6966FBE1809D802DF512964B01AC293F7BE
        // setStorage({
        //   token: res.data.token,
        //   userInfo: { avatarUrl, nickName }
        // }).then(() => {
        //   // getStorageUserInfo()
        //   Taro.reLaunch({url: '/pages/index/index'})
        // })
        Taro.setStorageSync('token', res.data.token)
        Taro.hideLoading()

        Taro.navigateBack()
        // Taro.reLaunch({url: '/pages/index/index'})
      }
    } catch (error) {}
  }

  const getCode = () => {
    Taro.login({
      success: async (res) => {
        if (res.code) {
          setCode(res.code)
        } else {
          showToast('登录失败！')
        }
      }
    })
  }

  useDidShow(() => {
    getCode()
    getStorageUserInfo()
  })


   return (
     <View className={styles.authorization}>
       {
         !userImpower ? (
          <View  className={`${styles.user} ${styles.impower}`}>
          <View className={styles.iconBox}>
            <Image
              src={AappIcon}
              mode='widthFix'
              className={styles.img}
            />
          </View>
          <View className={styles.h1}>校园颂申请获得以下权限</View>
          <View className={styles.h2}>获取您的公开信息 （昵称,头像等）</View>
          <Button
            className={styles.btn}
            onClick={getUserInfoHandle}
          >
            授权获取用户信息
          </Button>
        </View>
         ) : (
          <View className={`${styles.login} ${styles.impower}`}>
            <View className={styles.iconBox}>
              <Image
                src={AappIcon}
                mode='widthFix'
                className={styles.img}
              />
            </View>
            <View className={styles.h1}>校园颂申请获取手机号信息</View>
            <Button
              className={styles.btn}
              openType='getPhoneNumber'
              onGetPhoneNumber={getPhoneNumberHandle}
            >
              手机号快捷登录
            </Button>
          </View>
         )
       }
     </View>
   );
 }

 export default connect(({ user }) => ({
  user
}), dispatch => ({
  dispatch
}))(Authorization)
